<?php

namespace IDock\Insurance\CHAC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\CHAC\Request\AllCHACRequest;
use IDock\Insurance\CHAC\Request\DPremiumInquiryRequest;
use IDock\Insurance\CHAC\Request\EUnderwritingRequest;
use IDock\Insurance\CHAC\Response\AllCHACResponse;
use Throwable;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $config;

    public function execute(Request $request): Response
    {
        /*** @var AllCHACRequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));

        $request->setHeaders([]);

        $request = $this->sign($request);

        if ($request instanceof DPremiumInquiryRequest or $request instanceof EUnderwritingRequest) {
            $bizParam = $request->soapDataBuild($request->generate());
        } else {
            $bizParam = $this->generate($request);
        }

        $request->setBizParam($bizParam);

        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        $requestData = $request->generate();

        return $requestData;
    }


    public function sign(Request $request): Request
    {
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /*** @var AllCHACRequest $request */
        /*** @var AllCHACResponse $response */

        $response = $request->request($request);

        $response->setVisitor($request->getVisitor());

        $isTestResponse = $GLOBALS['testResponse'] ?? '';

        if (!$isTestResponse) {
            $request->responseAfterLogs($response->result ?: $response->getBody(), $response->isSuccess());
        }

        if ($response->isSuccess()) {
            $response->printerInit();
        } else {
            $request->errorLogs($request->getRequestId(),$request->getBizParam());
        }

        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     * @return bool
     */
    public function encrypt(Request $request): bool
    {
        return true;
    }

    public function decrypt(AllCHACResponse $response): bool
    {
        return true;
    }
}
